<?php
declare (strict_types=1);

namespace app\api\middleware;

use Closure;
use ffhome\common\util\CommonUtil;
use ffhome\frame\service\SystemLogService;
use think\Request;

/**
 * 系统操作日志中间件
 */
class SystemLog
{
    public function handle(Request $request, Closure $next)
    {
        $method = strtolower($request->method());
        if (in_array($method, ['get', 'post', 'put', 'delete'])) {
            $url = $request->url();
            $ip = CommonUtil::getRealIp();
            $params = $request->param();
            if (isset($params['s'])) {
                unset($params['s']);
            }
            $data = [
                'user_id' => currentMember()['id'],
                'url' => $url,
                'method' => $method,
                'ip' => $ip,
                'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                'useragent' => $_SERVER['HTTP_USER_AGENT'],
                'create_time' => date('Y-m-d H:i:s'),
            ];
            (new SystemLogService())->save($data);
        }
        return $next($request);
    }
}